<template>
  <div class="device-list">
    <!-- <ChartsTable :ChartsTableList="ChartsTableList"></ChartsTable> -->
    <el-collapse-transition>
      <card-search v-if="searchCardShow">
        <el-form label-width="70px" :inline="true" style="position: relative">
          <div v-show="moreSearch">
            <el-form-item label="权限类型"
              ><el-input
                v-model="input"
                placeholder="请输入项目名称/ 项目地址/ 项目简介/ 管理员/ 备注信息"
                style="width: 150px; margin-right: 10px"
                clearable
            /></el-form-item>
            <el-form-item>
              <el-button class="btn-search" round icon="el-icon-search" size="medium"
                >搜索</el-button
              >
              <el-button class="btn-search" round icon="el-icon-refresh" size="medium"
                >重置</el-button
              >
            </el-form-item>
          </div>
          <!-- <el-form-item style="position: absolute; top:0px;right:20px;cursor: pointer;color:#2085ea">

            <span @click="()=>{moreSearch=!moreSearch}">{{ moreSearch?'收起更多搜索':'展开更多搜索' }}</span><i :class="moreSearch?'el-icon-caret-top':'el-icon-caret-bottom'" />
          </el-form-item> -->
        </el-form>
      </card-search>
    </el-collapse-transition>

    <el-tabs style="margin: 20px" type="card" @tab-click="handleClickTab">
      <el-tab-pane
        v-for="(item, index) in devTypeList"
        :key="index"
        :label="item.dictLabel"
        :name="item.dictValue"
    /></el-tabs>
    <CardTable style="height: calc(100vh - 150px)">
      <div class="card-table-header">
        <div class="card-table-header-btns">
          <el-button
            v-if="isSuperAdmin || hasPermission('system:dnDevice:weChatRoleSet')"
            class="btn-search"
            size="small"
            icon="el-icon-edit"
            @click="handleClick('changeMiniPermissiom')"
            >小程序端权限设置</el-button
          >
          <el-input
            v-model="input"
            placeholder="请输入设备ID/ 名称/ 安装位置/ 备注信息"
            style="width: 340px; margin-left: 10px"
            clearable
            size="small"
          >
            <el-button slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </div>
        <div class="card-table-header">
          <table-action
            :table-header="filteredTableHeader"
            :eye-show="true"
            :search-show="true"
            @check-change="handleCheckChange"
            @search-click="handleSearchClick"
            @eye-click="handleEyeClick"
            @init-click="handleInitClick"
          />
        </div>
      </div>
      <el-table
        v-if="eyeCardShow"
        :key="tableKey"
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        :header-cell-style="{ background: '#eff3f8', color: '#333' }"
        stripe
        size="small"
        :max-height="tableHeight"
        @selection-change="handleSelectionChange"
        highlight-selection-row
        border
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          v-for="item in filteredTableHeader"
          v-if="item.visible"
          :key="item.prop"
          :label="item.title"
          :min-width="item.width"
          :prop="item.prop"
          :show-overflow-tooltip="true"
          :align="item.align"
          sortable
          :fixed="item.fixed"
        >
          <template #default="scope">
            <!-- 联网状态 -->
            <span v-if="item.prop === 'personInCharge'">
              <span
                :class="scope.row[item.prop] == '在线' ? 'table-online' : 'table-offline'"
              >
                {{ scope.row[item.prop] }}</span
              >
            </span>

            <span v-else>
              {{ scope.row[item.prop] }}
            </span>
          </template>
        </el-table-column>
      </el-table>
      <div v-else class="eye-list">
        <div v-for="(item, index) in tableData" class="eye-list-item">
          <div class="eye-list-item-left">
            <img src="https://kt.xinnuanyun.com/suittc_kt/img/kt_dev.png" alt="" />
            <div class="eye-list-item-left-template">23</div>
            <div>智能空调</div>
            <div>KT0020002022020</div>
          </div>
          <div class="eye-list-item-right">
            <div>
              <svg-icon
                icon-class="switch"
                class-name="card-panel-icon"
                style="width: 16px; height: 16px"
              />
              <span style="padding: 0 5px">开机状态:</span>
              <span class="open">开机</span>
            </div>
            <div>
              <svg-icon icon-class="rightCircle" class-name="card-panel-icon" />
              <span style="padding: 0 5px">联网状态:</span>
              <span class="close">在线</span>
            </div>
          </div>
        </div>
      </div>
      <XyPagination
        :total="total"
        :pageSizeNum="pageSize"
        :pageNum="currentPage"
        @pagination="handlerPagination"
      ></XyPagination>
    </CardTable>
    <el-dialog
      title="批量设置当前已勾选的设备权限"
      :visible.sync="dialogVisible"
      width="600px"
      custom-class="mini-permissions-dialog"
    >
      <el-card>
        <el-form class="set-permission" label-width="150px">
          <el-form-item label="小程序端权限类别:">
            <el-select v-model="value" placeholder="请选择">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-card>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
import CardSearch from "@/components/CardSearch";
import CardTable from "@/components/CardTable";
import TableAction from "@/components/TableAction";
import ChartsTable from "@/components/ChartsTable";
import XyPagination from "@/components/XyPagination";
import { hasPermission, isSuperAdmin } from "@/utils/hasBtnPermission";
import { queryDictData } from "@/api/systemmanagement";
export default {
  name: "DevicePermissionList",
  components: {
    CardSearch,
    CardTable,
    TableAction,
    ChartsTable,
    XyPagination,
  },
  data() {
    return {
      tableKey: 0, // 用于强制刷新表格
      searchCardShow: false,
      moreSearch: true,
      input: "",
      currentPage: 1,
      pageSize: 20,
      total: 0,
      tableHeight: 500,
      currentTabLabel: "全部类型",
      dialogVisible: false,
      options: [
        {
          value: "选项1",
          label: "黄金糕",
        },
        {
          value: "选项2",
          label: "双皮奶",
        },
        {
          value: "选项3",
          label: "蚵仔煎",
        },
        {
          value: "选项4",
          label: "龙须面",
        },
        {
          value: "选项5",
          label: "北京烤鸭",
        },
      ],
      value: "",
      tableHeader: [
        {
          title: "项目ID",
          prop: "projectName",
          width: "130",
          visible: true,
          align: "left",
          fixed: true,
        },
        {
          title: "设备名称",
          prop: "projectAdmin",
          width: "100",
          visible: true,
          align: "left",
          fixed: true,
        },
        {
          title: "所属项目",
          prop: "company",
          width: "150",
          visible: true,
          align: "left",
        },
        {
          title: "设备分组",
          prop: "totleNum",
          width: "120",
          visible: true,
          align: "center",
        },
        {
          title: "设备安装位置",
          prop: "onlineNum",
          width: "200",
          visible: true,
          align: "center",
        },
        {
          title: "子设备类型",
          prop: "offlineNum",
          width: "120",
          visible: true,
          align: "center",
        },
        {
          title: "联网状态",
          prop: "personInCharge",
          width: "100",
          visible: true,
          align: "center",
        },
        {
          title: "小程序端权限类别",
          prop: "address",
          width: "100",
          visible: true,
          align: "center",
        },
      ],
      tableData: [
        {
          projectName: "KTWG15980001",
          projectAdmin: "智能空调1",
          company: "香缇澜山二期",
          totleNum: "-",
          onlineNum: "-",
          offlineNum: "空调交流lora",
          personInCharge: "在线",
          address: "21.9℃",
        },
      ],
      multipleSelection: [],
      activeIndex: 0,
      eyeCardShow: true,
      ChartsTableList: [
        {
          name: "设备总数",
          type: "total",
          number: 99,
          icon: "echartCardTotal",
        },
        {
          name: "在线数量",
          type: "devOnline",
          number: 55,
          icon: "echartCardOnline",
        },
        {
          name: "离线数量",
          type: "devoffline",
          number: 35,
          icon: "echartCardOffline",
        },
        {
          name: "预警数量",
          type: "warn",
          number: 35,
          icon: "echartCardWarn",
        },
      ],
    };
  },
  computed: {
    // 传递给table-action组件的表头数据，根据当前标签页状态过滤
    filteredTableHeader() {
      if (this.currentTabLabel !== "全部类型") {
        // 当不是"全部类型"标签页时，过滤掉"子设备类型"列
        return this.tableHeader.filter((item) => item.title !== "子设备类型");
      } else {
        // 当是"全部类型"标签页时，显示所有列
        return this.tableHeader;
      }
    },
    isSuperAdmin() {
      return isSuperAdmin();
    },
  },
  mounted() {
    this.calculateTableHeight();
    this.loadDictData("sys_sub_dev_type", "devTypeList");
    this.initTable();
  },
  methods: {
    initTable() {},
    handlerPagination(page) {
      this.currentPage = page.pageNum;
      this.pageSize = page.pageSize;
      this.initTable();
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      if (this.multipleSelection.length > 0) {
        this.btnDisabled = false;
      } else {
        this.btnDisabled = true;
      }
    },
    handleClick(field) {
      switch (field) {
        case "changeMiniPermissiom":
          if (this.multipleSelection.length > 0) {
            this.dialogVisible = true;
          } else {
            this.$message.error("请选择要操作的设备!");
          }
          break;
        default:
          break;
      }
    },
    handleClickTab(tab, event) {
      this.currentTabLabel = tab.label;
      // 更新表格显示（如果需要根据标签类型过滤数据，可以在这里处理）
      this.tableKey += 1;
      this.initTable();
    },
    // 处理表头显示隐藏
    handleCheckChange(checkedValues) {
      this.tableHeader.forEach((item) => {
        // 对于"子设备类型"列，需要考虑当前标签页状态
        if (item.title === "子设备类型") {
          // 如果是"全部类型"标签页，则根据用户选择决定是否显示
          // 如果是其他标签页，则始终隐藏
          if (this.currentTabLabel === "全部类型") {
            item.visible = checkedValues.includes(item.prop);
          } else {
            item.visible = false;
          }
        } else {
          // 其他列按正常逻辑处理
          item.visible = checkedValues.includes(item.prop);
        }
      });
      this.tableKey += 1;
    },
    async loadDictData(dictType, targetProperty) {
      try {
        // 调用 store 中的字典查询方法，传入字典类型
        const data = await this.$store.dispatch("dict/queryDictData", dictType);
        // 根据接口返回的数据格式进行处理
        if (dictType == "sys_sub_dev_type") {
          this[targetProperty] = [{ dictLabel: "全部类型", dictValue: "" }, ...data];
        } else {
          this[targetProperty] = [{ dictLabel: "所有", dictValue: "" }, ...data];
        }
      } catch (error) {
        this.$message.error("获取数据失败");
      }
    },
    handleSearchClick() {
      console.log("搜索按钮点击");
      this.searchCardShow = !this.searchCardShow;
    },
    handleEyeClick() {
      this.eyeCardShow = !this.eyeCardShow;
    },
    handleInitClick() {
      this.initTable();
    },
    hasPermission(permission) {
      return hasPermission(permission);
    },
    calculateTableHeight() {
      // 根据容器实际高度计算表格高度
      this.$nextTick(() => {
        const container = this.$refs.multipleTable.$el?.parentElement;
        if (container) {
          // 减去表头和其他元素的高度
          this.tableHeight = container.clientHeight - 120; // 120为估计的其他元素高度
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.eye-list {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr 1fr;
  gap: 20px;
  .eye-list-item {
    border: 1px solid #e7eaec;
    padding: 20px;
    display: flex;
    color: #676a6c;
    font-size: 13px;
    .eye-list-item-left {
      position: relative;
      img {
        width: 130px;
        height: 130px;
      }
      .eye-list-item-left-template {
        position: absolute;
        top: 42px;
        left: 42px;
        font-size: 34px;
        font-weight: bold;
      }
      div {
        line-height: 24px;
        text-align: center;
        font-weight: bold;
      }
    }
    .eye-list-item-right {
      margin-top: 30px;
      margin-left: 10px;
      font-size: 14px;
      line-height: 26px;
      .open {
        color: #fff;
        background: #1ab394;
        border-radius: 10px;
        font-weight: bold;
        font-size: 12px;
        padding: 2px 4px;
      }
      .close {
        color: #fff;
        background: #ed556e;
        border-radius: 10px;
        font-weight: bold;
        font-size: 12px;
        padding: 2px 4px;
      }
    }
  }
}
.mini-permissions-dialog {
  .set-permission {
    height: 200px;
  }
}
</style>
<style lang="scss">
.device-list {
  .el-tabs--card > .el-tabs__header .el-tabs__item {
    width: 150px;
    text-align: center;
    background-color: #dfe6ec;
    color: #3d3d3d;
    border-top-left-radius: 10px;
    // border-top-right-radius: 15px;
    margin-left: -10px;
    border: 1px solid #fff;
  }
  .el-tabs--card > .el-tabs__header .el-tabs__item:first-child {
    margin-left: 0;
  }
  .el-tabs--card > .el-tabs__header .el-tabs__item.is-active {
    background-color: #165eff;
    color: #fff;
  }
  .el-tabs--card > .el-tabs__header .el-tabs__nav {
    border: 1px solid #fff;
  }
  .el-tabs__nav-wrap {
    margin-top: -2px;
  }
  .el-tabs--card > .el-tabs__header {
    border-bottom: 1px solid #dfe6ec;
    margin: 0;
  }
}
</style>
